package controller.teacher;

import entity.TeacherEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.TeacherService;
import service.impl.TeacherServiceImpl;
import controller.student.StudentServlet;
import util.BaseResult;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(urlPatterns = "/updateTeacher")
public class UpdateTeacherServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(StudentServlet.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json;charset=UTF-8");
            BufferedReader reader = req.getReader();
//            Map<String, Object> body = objectMapper.readValue(reader, new TypeReference<HashMap<String, Object>>() {
//            });

            TeacherEntity teacher = objectMapper.readValue(req.getReader(), TeacherEntity.class);
//            teacher.setId((String) body.get("teacherId"));
//            teacher.setAcademyId((String) body.get("academyId"));
//            teacher.setTeacherName((String) body.get("teacherName"));
//            teacher.setAge((Integer) body.get("age"));
//            teacher.setGender((Integer) body.get("gender"));
//            teacher.setPhoneNumber((String) body.get("phoneNumber"));
//            teacher.setDegree((String) body.get("degree"));

            TeacherService teacherService = new TeacherServiceImpl();
            teacherService.updateTeacherInfo(teacher);

            resp.setContentType("application/json;charset=UTF-8");

            BaseResult<Void> result = BaseResult.success();
            // 序列化并写入响应
            String jsonResponse = objectMapper.writeValueAsString(result);
            resp.getWriter().write(jsonResponse);
        } catch (Exception e) {
            logger.error("修改教师信息错误", e);

            BaseResult<Void> errorResult = BaseResult.failed(500, "修改教师信息失败: " + e.getMessage());

            resp.setContentType("application/json;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            String jsonError = objectMapper.writeValueAsString(errorResult);
            resp.getWriter().write(jsonError);
        }
    }
}
